<template>
  <el-card> 

  <div class="department-management">
    <!-- 操作栏 -->
    <div class="toolbar">
<!--      <el-input v-model="searchKeyword" placeholder="请输入部门名称" size="small" style="width: 200px; margin-right: 10px;" />
      <el-button type="primary" size="small" @click="handleSearch">搜索</el-button>-->
      <el-button type="success" size="small" @click="openAddDialog" style="margin-left: 10px;">新增年级</el-button>
    </div>

    <!-- 表格 -->
    <el-table :data="dataList" stripe border style="width: 100%; margin-top: 20px;">
      <el-table-column v-if="false" prop="id" label="部门ID" width="80" />
      <el-table-column prop="name" label="年级名称" />
      <el-table-column label="操作" width="180">
        <template slot-scope="scope">
          <el-button size="mini" type="primary" @click="openEditDialog(scope.row)">编辑</el-button>
          <el-button size="mini" type="danger" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!-- 新增/编辑对话框 -->
    <el-dialog :title="dialogTitle" :visible.sync="dialogVisible">
      <el-form :model="form" label-width="80px">
        <el-form-item label="年级名称">
          <el-input v-model="form.name" />
        </el-form-item>

      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleSubmit">确 定</el-button>
      </div>
    </el-dialog>
  </div>
  </el-card>

</template>

<script>
import api from '@/common/api';

export default {
  data() {
    return {
      searchKeyword: '',
      departments: [],
      dialogVisible: false,
      dialogTitle: '新增年级',
      form: {
        id: null,
        name: ''
      },
      dataList:[]
    };
  },
  computed: {
    filteredDepartments() {
      const keyword = this.searchKeyword.trim();
      if (!keyword) return this.departments;
      return this.departments.filter(d => d.name.includes(keyword));
    }
  },
  methods: {
    handleSearch() {
      // 搜索逻辑由 computed 属性处理
    },
    openAddDialog() {
      this.dialogTitle = '新增年级';
      this.form = { id: null, name: ''};
      this.dialogVisible = true;
    },
    openEditDialog(row) {
      this.dialogTitle = '编辑年级';
      this.form = { ...row };
      this.dialogVisible = true;
    },
/*    handleSubmit() {
      if (this.form.id) {
        // 修改逻辑
        const index = this.departments.findIndex(d => d.id === this.form.id);
        if (index !== -1) {
          this.departments.splice(index, 1, { ...this.form });
        }
      } else {
        // 新增逻辑
        const newId = this.departments.length
            ? Math.max(...this.departments.map(d => d.id)) + 1
            : 1;
        this.departments.push({ ...this.form, id: newId });
      }
      this.dialogVisible = false;
    },*/

    async handleSubmit() {
      try {
        if (this.form.id) {
          // 更新逻辑
          const res = await api.admin_updateleavels(this.form);
          if (res.status === 200) {  // 假设成功返回code为200
            const index = this.departments.findIndex(d => d.id === this.form.id);
            if (index !== -1) {
              this.departments.splice(index, 1, { ...this.form });
            }
            this.loading = true;
            this.getList();
            this.$message.success('更新成功');
          } else {
            this.$message.error(res.msg || '更新失败');
          }
        } else {
          // 新增逻辑
          const res = await api.admin_addleavels(this.form);
          if (res.status === 200) {
            // 使用后端返回的ID（推荐）
            const newDep = { ...this.form, id: res.data.id };
            this.departments.push(newDep);
            this.loading = true;
            this.getList();
            this.$message.success('新增成功');
          } else {
            this.$message.error(res.msg || '新增失败');
          }
        }
        this.dialogVisible = false;
        // 可选：重置表单
        this.form = { id: null, name: '' };
      } catch (error) {
        console.error('操作失败:', error);
        this.$message.error('请求失败，请检查网络');
      }
    },
    handleDelete(rowData) {
      this.$confirm('确认删除吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        // 传递整行数据到后台
        api.admin_deleteleavels(rowData)
            .then(res => {
              if (res.status === 200) {
                this.dataList = this.dataList.filter(d => d.id !== rowData.id);
                this.$message.success(res.msg || '删除成功');
                this.getList();

                // 如果需要特殊处理返回数据
                if (res.data?.needSpecialHandle) {
                  this.handleSpecialCase(res.data);
                }
              } else {
                this.$message.error(res.msg || '删除失败');
              }
            })
            .catch(err => {
              console.error('删除失败:', err);
              this.$message.error(err.response?.data?.msg || '删除失败，请重试');
            });
      }).catch(() => {
        // 用户点击取消
      });
    },
    async getList(){
     const res =   await api.admin_getleavels()
      console.log(res,'res')
      this.dataList = res.data.data
    }
  },
  created() {
    this.getList()
  }
};
</script>

<style scoped>
.department-management {
  padding: 20px;
}
.toolbar {
  display: flex;
  align-items: center;
}
</style>
